package com.enlighten.aio.user.service.Impl;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.enlighten.aio.db.mapper.DocumentMapper;
import com.enlighten.aio.db.mapper.UserMapper;
import com.enlighten.aio.db.model.Document;
import com.enlighten.aio.db.model.User;
import com.enlighten.aio.db.model.UserExample;
import com.enlighten.aio.db.model.out.UserOut;
import com.enlighten.aio.user.service.UserService;
import com.x.share.db.model.Pagination;
import com.x.share.mid.exception.HelperException;
import com.x.share.mid.prop.AliDayuProperties;
import com.x.share.mid.prop.AliOSSProperties;
import com.x.share.mid.utils.AliOSSUtils;
import com.x.share.mid.utils.MD5Util;
import com.x.share.mid.utils.ToolUtil;
import com.x.share.mid.utils.ValidateCode;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	UserMapper userMapper;
	@Resource
	AliOSSProperties aliOSSProperties;
	@Resource
	DocumentMapper documentMapper;
	@Resource
	AliDayuProperties aliDayuProperties;
	
	@Override
	public Pagination<User> getAllUser(Integer pageNo, Integer pageSize) {
		Pagination<User> page = new Pagination<>(pageNo, pageSize);
		UserExample ue = new UserExample();
		List<User> list = userMapper.selectByExampleWithBLOBs(ue);
		int count = (int) userMapper.countByExample(ue);
		page.setItems(list);
		page.setRecords(count);
		return page;
	}

	@Override
	public boolean insertUser(User u) {
		int num = userMapper.insertSelective(u);
		if(num==0) {
			throw new HelperException("添加失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	public boolean editUser(User u) {
		int num =userMapper.updateByPrimaryKeyWithBLOBs(u);
		if(num == 0) {
			throw new HelperException("编辑失败");
		}
		return false;
	}

	@Override
	public boolean delUser(Long id) {
		int num = userMapper.deleteByPrimaryKey(id);
		if(num == 0) {
			throw new HelperException("删除失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	public User getUserById(Long id) {
		User user = userMapper.selectByPrimaryKey(id);
		return user;
	}

	@Override
	@Transactional
	public boolean updateUser(User u,List<MultipartFile> files) {
		if(files.size()==0) {
			throw new HelperException("图片为空");
		}else {
			for (MultipartFile file : files) {
				int docNum=0;
				String key=null;
				try {
					key = AliOSSUtils.uploadToOSS(aliOSSProperties, file.getInputStream());
				} catch (IOException e) {
					e.printStackTrace();
				}
				Document d = new Document();
				String fileName = file.getOriginalFilename();
				String url = aliOSSProperties.getBucket() + "." + aliOSSProperties.getGateway() + "/" + key;
				String name = fileName.substring(0, fileName.indexOf("."));
				d.setName(name);
				d.setOssId(key);
				d.setCreateDate(ToolUtil.getTime(0));
				d.setUrl(url);
				d.setUserId(u.getId());
				docNum = documentMapper.insertSelective(d);
				if(docNum != 1) {
					AliOSSUtils.removeFromOSS(aliOSSProperties, key);
					throw new HelperException("上传文档失败");
				}
				//u.setSequence(name);
			}
		}
		int	num = userMapper.updateByPrimaryKeySelective(u);
		if(num != 1) {
			throw new HelperException("更新信息失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	public boolean RegisterUser(User u) {
		UserExample ue = new UserExample();
		ue.or().andNicknameEqualTo(u.getNickname());
		List<User> list = userMapper.selectByExample(ue);
		if(list.size()==0) {
			ue.or().andEmailEqualTo(u.getEmail());
			List<User> list2 = userMapper.selectByExample(ue);
			if(list2.size()==0) {
				String password = MD5Util.encryptPassword(u.getPassword());
				u.setPassword(password);
				u.setNickname(u.getNickname());
				u.setEmail(u.getEmail());
				int num = userMapper.insertSelective(u);
				if(num != 1) {
					throw new HelperException("注册失败");
				}
				return num > 0 ? true : false;
			}else {
				throw new HelperException("邮箱被占用");
			}
		}else {
			throw new HelperException("用户名已存在");
		}
		
	}
	
	/**
	 * 验证码
	 * Lu
	 *2018年8月27日
	 */
	public String getCode(HttpServletRequest request) {
		ValidateCode validateCode = new ValidateCode();
		String code = validateCode.getCode();
		HttpSession session = request.getSession();
		session.setAttribute("code", code);
		return code;
	}

	@Override
	public boolean login(String nickName, String password, String code, HttpServletRequest request) {
		UserExample ue = new UserExample();
		ue.or().andNicknameEqualTo(nickName);
		List<User> list = userMapper.selectByExample(ue);
		password=MD5Util.encryptPassword(password);
		ue.or().andPasswordEqualTo(password);
		List<User> list2 = userMapper.selectByExample(ue);
		HttpSession session=request.getSession();
		String codes = (String) session.getAttribute("code");
		if(codes.equals(code)) {
			if(list.size()!=0) {
				if(list2.size()!=0) {
					return true;
				}else {
					throw new HelperException("密码错误");
				}
			}else {
				throw new HelperException("用户名不存在");
			}
		}else {
			throw new HelperException("验证码错误");
		}
	}

	@Override
	public List<UserOut> getUserInformation(Long id) {
		List<UserOut> list = userMapper.getUserInformation(id);
		return list;
	}
	
	public void sendSMS(String mobile) {
		Random rd = new Random();
		String code = String.valueOf(rd.nextInt(899999) + 100000);
	//	AliDayuUtils.sendSmsV2(aliDayuProperties, mobile, aliDayuProperties.getPhoneBindTMID(), param, "");
	}
}
